layui.use(['form', 'table', 'eleTree', 'fsoft'], function () {
	var $ = layui.$
		, form = layui.form
		, table = layui.table
		, eleTree = layui.eleTree
		, fsoft = layui.fsoft;
	form.render();
	var dictId = $("#dictId").val();
	var tableId = "fsoftItemTable";
	var treeId = "fsoft-itemTrees";
	var searchFormId = "fsoftForm";

	var itemTree = eleTree.render({
		elem: '#' + treeId,
		method: 'post',
		url: layui.cache['contentPath'] + '/sys-dict/findItemTrees?dictId=' + dictId,
		request: { name: "title", key: "id", children: "children" },
		highlightCurrent: true,
		defaultExpandAll: true,
		expandOnClickNode: false,
		showLine: true
	});
	//选中的节点
	var currTreeNode = {};
	// 节点点击事件
	eleTree.on("nodeClick(" + treeId + ")", function (d) {
		currTreeNode = d.data.currentData;
		$("#parents").val(currTreeNode.id);
		active.doSearch();
	});

	//字典列表刷新
	table.render({
		elem: '#' + tableId
		, method: 'post'
		, toolbar: '#batchBtnToolbar'
		, url: layui.cache['contentPath'] + '/sys-dict/findItemList',
		where: form.val(searchFormId),
		cols: [[
			{ type: 'checkbox', fixed: 'left' },
			{ field: 'code', title: '配置编码', width: 150, align: 'center', style: "text-align:left;", sort: true },
			{ field: 'name', title: '配置名称', width: 200, align: 'center', style: "text-align:left;" },
			{ field: 'parentName', title: '上级配置', width: 200, align: 'center', style: "text-align:left;" },
			{ field: 'dictName', title: '所属字典', width: 120, align: 'center', style: "text-align:left;" },
			{ fixed: 'right', width: 150, align: 'center', title: '操作', toolbar: '#btnRowTool' }
		]],
		page: true,
		limit: 10,
		limits: [10, 20, 50, 100],
		height: 'full-104'
	});
	var active = {
		doSearch: function (params) {
			if (params == undefined || params == null) {
				params = $.extend({}, form.val(searchFormId));
			} else {
				$.extend({ params }, form.val(searchFormId));
			}
			table.reload(tableId, { where: params });
		}
		, removeBatch: function (data) { //批量删除
			if (data == undefined || data.length == 0) {
				fsoft.warnMsg("请至少选择1条记录！");
				return false;
			}
			var ids = new Array();
			$.each(data, function (idx, item) {
				ids.push(item.id);
			});
			var msg = "确认要删除当前记录？";
			if (ids.length > 1) {
				msg = "确认要删除已选中的（" + ids.length + "）条记录？";
			}
			fsoft.confirm("询问", msg, function (index) {
				fsoft.delete(layui.cache['contentPath'] + '/sys-dict/removeItem', ids, function (rs) {
					if (rs.code == 0) {
						fsoft.successMsg("删除成功");
						active.doSearch();
					} else {
						fsoft.errorMsg("删除失败！" + rs.msg);
					}
				});
				layer.close(index);
			});
		},
		showContentForm: function (data) {
			var url = layui.cache['contentPath'] + '/sys-dict/additem/' + $("#dictId").val();
			var title = "添加配置项";
			var params = ["parentId=" + $("#parents").val()];
			layer.open({
				type: 2, title: title
				, area: ['500px', '350px']
				, content: url + "?" + params.join("&")
				, end: function () {
					itemTree.reload();
					this.doSearch()
				}
			});
		},
		enable: function (data) {/*启用*/
			if (data == undefined || data.length == 0) {
				layer.msg("请至少选择一条记录", { icon: 7, time: 3000 });
				return;
			}
			var ids = new Array();
			for (var k = 0; k < data.length; k++) {
				ids.push(data[k].id);
			}
			layer.confirm("确认要启用已选中的（" + ids.length + "）个配置项？", function (index) {
				$.ajax({
					type: 'POST',
					url: layui.cache['contentPath'] + '/sys-dict/enableItem',
					data: JSON.stringify(ids),
					contentType: "application/json",
					success: function (rs) {
						rs = eval('(' + rs + ')');
						if (rs.code == 0) {
							layer.msg("启用成功", { icon: 1, time: 3000 });
							table.reload('table', { where: data.field });
						} else {
							layer.alert(rs.msg);
						}
					},
					error: function (status, errors) {
						layer.alert('请求错误，错误码：' + JSON.stringify(status));
					}
				});
			});
		},
		disable: function (data) { /*禁用*/
			if (data == undefined || data.length == 0) {
				layer.msg("请至少选择一条记录", { icon: 7, time: 3000 });
				return;
			}
			var ids = new Array();
			for (var k = 0; k < data.length; k++) {
				ids.push(data[k].id);
			}
			layer.confirm("确认要禁用已选中的（" + ids.length + "）个配置项？", function (index) {
				$.ajax({
					type: 'POST',
					url: layui.cache['contentPath'] + '/sys-dict/disableItem',
					data: JSON.stringify(ids),
					contentType: "application/json",
					success: function (rs) {
						rs = eval('(' + rs + ')');
						if (rs.code == 0) {
							layer.msg("禁用成功", { icon: 1, time: 3000 });
							table.reload('table', { where: data.field });
						} else {
							layer.alert(rs.msg);
						}
					},
					error: function (status, errors) {
						layer.alert('请求错误，错误码：' + JSON.stringify(status));
					}
				});
			});
		}
	};

	//搜索监听
	form.on('submit(sreach)', function (data) {
		table.reload(tableId, { where: data.field });
		return false;
	});
	table.on('toolbar(' + tableId + ')', function (obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
			case 'add':
				active.showContentForm();
				break;
			case 'removeBatch':
				active.removeBatch(checkStatus.data);
				break;
			case 'enable':
				active.enable(checkStatus.data);
				break;
			case 'disable':
				active.disable(checkStatus.data);
				break;
		}
	});
	//行操作监听 
	table.on('tool(' + tableId + ')', function (obj) {
		var data = obj.data;
		if (obj.event === 'edit') {
			xadmin.open('编辑配置项', layui.cache['contentPath'] + '/sys-dict/edititem/' + data.id, 500, 350);
		} else if (obj.event === 'del') {
			layer.confirm("确认要删除当前记录？", function (index) {
				$.ajax({
					type: 'POST',
					url: layui.cache['contentPath'] + '/sys-dict/removeItem',
					data: JSON.stringify([data.id]),
					contentType: "application/json",
					success: function (rs) {
						rs = eval('(' + rs + ')');
						if (rs.code == 0) {
							layer.msg("删除成功", { icon: 1, time: 3000 });
							table.reload('table', { where: data.field });
						} else {
							layer.alert(rs.msg);
						}
					},
					error: function (status, errors) {
						layer.alert('请求错误，错误码：' + JSON.stringify(status));
					}
				});
			});
		}
	});
});